import os
import socket
import threading
import time

global client_socket

def led_on():
    os.system("echo none > /sys/class/leds/led1/trigger")
    os.system("echo 1 > /sys/class/leds/led1/brightness")

def led_off():
    os.system("echo none > /sys/class/leds/led1/trigger")
    os.system("echo 0 > /sys/class/leds/led1/brightness")

def heartbeat_and_reconnect(host, port):
    global client_socket
    while True:
        try:
            # heart beat
            client_socket.sendall(b'HEARTBEAT')
        except socket.error as e:
            client_socket.close()
            # reconnect
            connect_to_server(host, port)
        time.sleep(0.1)  # heartbeat every 0.1 seconds

def connect_to_server(host, port):
    global client_socket
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect_ex((host, port))
    return client_socket

def receive_and_reply():
    global client_socket
    while True:
        try:
            message = client_socket.recv(1024)
            if not message:
                continue

            message_string = message.decode('utf-8')
            print("RCV: ", message_string)

            # handle commands
            if ("capture" in message_string):
                os.system("./capture.sh")
            if ("LED_ON" in message_string):
                led_on()
            if ("LED_OFF" in message_string):
                led_off()

            # must response ok
            response = "ok"
            client_socket.sendall(response.encode('utf-8'))
            print("SND: ", response)
        except socket.error as e:
            time.sleep(0.1) # heartbeat every 0.1 seconds

def main():
    host = '8.154.42.52'
    port = 9999

    connect_to_server(host, port)

    # 初始化 发送心跳帧并尝试重建tcp连接 的线程
    heartbeat_thread = threading.Thread(target=heartbeat_and_reconnect, args=(host, port))
    heartbeat_thread.daemon = True

    # 初始化 接收命令和发送执行情况 的线程
    receive_thread = threading.Thread(target=receive_and_reply, args=())
    receive_thread.daemon = True

    heartbeat_thread.start()
    receive_thread.start()

    while True:
        time.sleep(1)

if __name__ == '__main__':
    main()
